package com.wulaobo.aggregation;

import com.wulaobo.pojo.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author wuwenbo
 * @Date 2024/5/17 11:39
 * @ClassName: KeyByDemo
 * @Description: TODO
 */
public class KeyByDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

//        env.setParallelism(1);

        DataStreamSource<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_4", 1, 1),
                new WaterSensor("sensor_2", 2, 2),
                new WaterSensor("sensor_2", 2, 3),
                new WaterSensor("sensor_4", 3, 4),
                new WaterSensor("sensor_5", 4, 5)
        );

        //todo 方式一：使用Lambda表达式
//        KeyedStream<WaterSensor, String> keyedStream = stream.keyBy(e->e.getId());
        //todo 方式一：使用Lambda表达式
        KeyedStream<WaterSensor, String> keyedStream = stream.keyBy(WaterSensor::getId);

//        KeyedStream<WaterSensor, Integer> keyedStream = stream.keyBy(new KeySelector<WaterSensor, Integer>() {
//            @Override
//            public Integer getKey(WaterSensor value) throws Exception {
//                return value.getTs();
//            }
//        });

        keyedStream.print();

        env.execute();

    }

}
